//
//  AppDelegate.m
//  QoilPublic
//
//  Created by zhuang on 16/7/1.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "AppDelegate.h"
#import "QMainVC.h"
#import "IQBarButtonItem.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "UMSocial.h"
#import "QNavigationVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import "UMSocialWechatHandler.h"
#import "QPaySuccessVC.h"
#import "UIImage+GIF.h"
#import "JPUSHService.h"
#import "QAllOrderMoreVC.h"
#import "QDetailsOrderVC.h"
#import <AdSupport/AdSupport.h>
#import "QLoginVC.h"
#import "UMSocialQQHandler.h"
#import <UserNotifications/UserNotifications.h>
#import "QPayPlayBoxView.h"
#import "QNoPayOrderModel.h"
#import "QForgetPayPassWordVC.h"
#import "QPaySuccessVC.h"
#import "QShowPayView.h"
#import "Reachability.h"
#import "UMMobClick/MobClick.h"
#import "QAdvertisementView.h"
#import "QAdvertisementModel.h"
#import "QOilTabBarController.h"
#import "QSendingMapVC.h"
#import "FileManager.h"
#import <ImageIO/ImageIO.h>
#import "SPUncaughtExceptionHandler.h"
#import "PushVC.h"
#import "QAllOrderMoreVC.h"
#import <Bugly/Bugly.h>
#import "QActivityWebVC.h"
#import "WebVC.h"
#import "HomePingJiaVC.h"
@interface AppDelegate ()<WXApiDelegate,UIAlertViewDelegate,JPUSHRegisterDelegate,UIAlertViewDelegate>

@end

@implementation AppDelegate{

    UIImageView *_gifImage;
    NSString *_passWordStr;
    NSString *_orderId;
    NSString *_moneys;
    
    NSString *_first;
    
    UIControl *_maskView;
    QPayPlayBoxView *_playView;
    NSURL *_gifImageUrl;
    NSString *_url;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   
    _first = @"first";
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [self getAdvertisingImage];
    [Bugly startWithAppId:BuglyKey];
    [self ExceptionHandling];//异常捕获
    [self registerSDK_Key];//注册第三方key
    [self setupAttbuilts];//设置键盘
    [self versionUpdateRequest];//版本更新监听
    [self getUUID];//上传机器码
    [self registerJPHSHWithApplication:application LaunchOptions:launchOptions];
    [self.window makeKeyAndVisible];
    [QViewUtility chooseRootViewController:self.window];   
    [self show_gifImage];//gif
    [self registerNetwork];//网络监听
    [self createNopayView];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiNoPay) name:kNotificationNoPayOrders object:nil];
    
//    [self gainOrderInfo];
   
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(HomePingJiaNotification) name:@"HomePingJiaNotification" object:nil];
    if (launchOptions) {
        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        //这个判断是在程序没有运行的情况下收到通知，点击通知跳转页面
        if (remoteNotification) {
            NSLog(@"推送消息==== %@",remoteNotification);
            WebVC * VC = [[WebVC alloc]init];
            VC.url = [remoteNotification objectForKey:@"content"];
            UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
            [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];
        }
    }
    
    return YES;
}
- (void)HomePingJiaNotification{
    
    
     self.window.rootViewController = [[QOilTabBarController alloc] init];
}
- (void)gainOrderInfo{
    
    NSString *url = [QParamService urlWithAction:@"order/findUserOrderEvaluate"];
    NSDictionary *params = [QParamService GainStarText];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        
        if([basModel.result isEqualToString:@"success"]){
            
            NSArray *array = basModel.items;
            
            if (array.count>0 ) {
                
                 [self chooseRootViewController:self.window];
                
            }else{
                
                
            }
          
        }else{
            
        }
    }];
}
- (void)chooseRootViewController:(UIWindow *)window{
    
    HomePingJiaVC *vc = [[HomePingJiaVC alloc]init];
   
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
   nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
     [window.rootViewController presentViewController:nav animated:YES completion:nil];

}

- (void)registerJPHSHWithApplication:(UIApplication *)application LaunchOptions:(NSDictionary *)launchOptions{
    

    // 1.注册系统通知
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    // 2.注册极光推送
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [JPUSHService setupWithOption:launchOptions appKey:JappKey
                          channel:Jchannel
                 apsForProduction:JisProduction
            advertisingIdentifier:advertisingId];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    [JPUSHService setBadge:0];
    
    
    
}
- (void)showAdvertisementView{
    // 1.判断沙盒中是否存在广告图片，如果存在，直接显示
    NSString *filePath = [self getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) {
        //图片存在
        QAdvertisementView *advertiseView = [[QAdvertisementView alloc] initWithFrame:self.window.bounds];
        advertiseView.filePath = filePath;
        [advertiseView show];
    }
 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//设置状态栏
    
}

/**
 *  判断文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

/**
 *  初始化广告页面
 */
- (void)getAdvertisingImage
{
    
     [self deleteOldImage];
    NSString *url = [QParamService urlWithAction:@"indexAdvert"];
    NSDictionary *param = [QParamService indexAdvertWithSrcId:@"0" SrType:@"19"];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            if ([[basModel.items objectForKey:@"imgvoList"] count]) {
                NSArray * arr = [QAdvertisementModel mj_objectArrayWithKeyValuesArray:[basModel.items objectForKey:@"imgvoList"]];
                QAdvertisementModel *model = [arr objectAtIndex:0];
                NSString *imageUrl = model.imgUrl;
                
                NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
                NSString * imageName = stringArr.lastObject;
                
                // 拼接沙盒路径
                NSString *filePath = [self getFilePathWithImageName:imageName];
                BOOL isExist = [self isFileExistWithFilePath:filePath];
                if (!isExist){// 如果该图片不存在，则删除老图片，下载新图片
                    
                    [self downloadAdImageWithUrl:imageUrl imageName:imageName adUrl1:model.url];
                    
                }
            }
        }else{
            
        }
    }];
}

/**
 *  下载新图片
 */
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName adUrl1:(NSString *)adUrl1
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名称
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [kUserDefaults setValue:imageName forKey:adImageName];
            //保存广告链接
            [kUserDefaults setValue:adUrl1 forKey:adUrl];
            [kUserDefaults synchronize];
            
        }else{
            NSLog(@"保存失败");
        }
        
    });
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage
{
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  根据图片名拼接文件路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName
{
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}

- (void)getUUID{
    NSString *UUID = [QParamService getUUID];
    NSString *url = [QParamService urlWithAction:@"addMacInfo"];
    NSDictionary *param = [QParamService addMacInfoWithMac:UUID UmdUids:@""];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            CLog(@"上传机器码成功====%@",UUID);
        }else{
        }
    }];
}

- (void)noteWorktype{

    Reachability * reach = [Reachability reachabilityForInternetConnection];
    NSString * tips = @"";
    switch (reach.currentReachabilityStatus)
    {
        case NotReachable:
            tips = @"无网络连接";
            break;
            
        case ReachableViaWiFi:
            tips = @"Wifi";
            break;
            
        case ReachableViaWWAN:
            CLog(@"移动流量");
        case kReachableVia2G:
            tips = @"2G";
            break;
            
        case kReachableVia3G:
            tips = @"3G";
            break;
            
        case kReachableVia4G:
            tips = @"4G";
            break;
    }
    if([tips isEqualToString:@"2G"]){
    
      [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"您现在的网络处于2G模式下,传输速度较慢,可能会导致部分功能异常,如遇网络异常请多次尝试或在3G/4G网络下再试" btnTitle:showAlertBtnTitle type:2 myBlock:^{}];
    }

}

- (void)notifiNoPay{
    if([QUserInfo sharedInfo].loginModel){
        if([QUserInfo sharedInfo].isShow == NO){
            //[self requestNoPayOrderData];
        }
    }
}

#pragma mark --- 注册第三方key
- (void)registerSDK_Key{

    [WXApi registerApp:WXappID withDescription:@"oilWXid"];//微信支付 分享
    [UMSocialWechatHandler setWXAppId:WXappID appSecret:WXappSecret url:@""];
    [UMSocialQQHandler setQQWithAppId:QQappID appKey:QQappSecret url:@""];//这里填分享到qq空间的url

    [UMSocialData setAppKey:UmengKey];//umeng分享
    UMConfigInstance.appKey = UmengKey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//统计
    
    //[AMapLocationServices sharedServices].apiKey = GDMapKey;//高德地图

    [AMapServices sharedServices].apiKey = GDMapKey;
}

#pragma mark --- 监听网络变化
- (void)registerNetwork{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatusDidChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    
}
- (void)networkStatusDidChanged:(NSNotification*)notification {
    if (![[AFNetworkReachabilityManager sharedManager] isReachable]) {
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"网络连接失败" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        [QUserInfo sharedInfo].isHaveNetWork = NO;
    }else{
        [QUserInfo sharedInfo].isHaveNetWork = YES;
    }
     [self noteWorktype];//监听是2g网
}

#pragma mark --- 设置键盘
- (void)setupAttbuilts{

    [[IQKeyboardManager sharedManager]setEnable:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;//全局设置隐藏toobar
    
    QLoginModel *loginModel = [QDataUtility getLoginModel];
    [QUserInfo sharedInfo].loginModel = loginModel;
    CLog(@"登录为=====%@",[QUserInfo sharedInfo].loginModel);
}
#pragma mark --- gif
- (void)show_gifImage{

    // 获取图片根据图片大小进行切割
    if(iphone4x_3_5){
        _gifImageUrl = [[NSBundle mainBundle] URLForResource:@"launch4xGif" withExtension:@"gif"];
    }else{
        _gifImageUrl = [[NSBundle mainBundle] URLForResource:@"launchGif" withExtension:@"gif"];
    }
    
    //获取Gif图的原数据
    
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)_gifImageUrl, NULL);
    
    //获取Gif图有多少帧
    
    size_t gifcount = CGImageSourceGetCount(gifSource);
    
    
    
    NSMutableArray *imageS = [[NSMutableArray alloc] init];
    
    
    for (NSInteger i = 0; i < gifcount; i++) {
        
        //由数据源gifSource生成一张CGImageRef类型的图片
        
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        
        UIImage *image = [UIImage imageWithCGImage:imageRef];
        
        [imageS addObject:image];
        
        CGImageRelease(imageRef);
    }
    
    
    //把数组图片通过imageView的动画添加  然后开始动画
    
    _gifImage = [[UIImageView alloc]initWithFrame:self.window.bounds];//初始化
    
    _gifImage.image = imageS.firstObject;
    
    _gifImage.animationImages = imageS;
    
    //动画的总时长(一组动画坐下来的时间 6张图片显示一遍的总时间)
    
    _gifImage.animationDuration = 2.5;
    
    _gifImage.animationRepeatCount = 0;//动画进行几次结束
    
    [_gifImage startAnimating];//开始动画
    
    
    
    _gifImage.userInteractionEnabled = YES;
    
    [[UIApplication sharedApplication].keyWindow addSubview:_gifImage];
    
    _gifImage.contentMode = UIViewContentModeScaleAspectFill;
    
    [self performSelector:@selector(removeGif) withObject:nil afterDelay:3.5];
    [self performSelector:@selector(showAdvertisementView) withObject:nil afterDelay:3.6];
}

- (void)removeGif{
     [_gifImage stopAnimating];//停止动画
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//设置状态栏
    _gifImage.alpha = 1;
    [UIView animateWithDuration:1 animations:^{
        _gifImage.alpha = 0;
    } completion:^(BOOL finished) {
        [_gifImage removeFromSuperview];
        _gifImage = nil;
    }];
}

#pragma mark --- 版本更新
- (void)versionUpdateRequest{
    NSString *url = [QParamService urlWithAction:@"upgradeVersion"];
    NSDictionary *param = [QParamService updateVersion:@"3"];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSDictionary *versionDic = [[NSBundle mainBundle] infoDictionary];
            NSString *currVersion = versionDic[@"CFBundleShortVersionString"];
            NSDictionary *dic = basModel.items;
            NSString *content = dic[@"content"];
            NSString *version = dic[@"version"];
            NSLog(@"======************===%@======%@",currVersion,version);
            if(![version isEqualToString:currVersion]){//更新
                UIAlertView *aler1 = [[UIAlertView alloc] initWithTitle:@"新版提示" message:[NSString stringWithFormat:@"油到了%@有新版本哦~\n%@",version,content] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                aler1.tag = 1;
                [aler1 show];
            }
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //新版本信息提示
    if(alertView.tag == 1){
        if(buttonIndex == 0){
            CLog(@"===");
        }else{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/you-dao-le/id1142912628?mt=8"]];
        }
    }else if(alertView.tag == 2){//另一个设备登陆提醒
    
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLoginSignOut object:nil];//退出登录通知
        
        if(buttonIndex == 0){
            
        }else{
            if(self.window.rootViewController){
                if(![QUserInfo sharedInfo].loginModel){
                    QLoginVC *vc = [[QLoginVC alloc] init];
                    [[QViewUtility getCurrentVC].navigationController pushViewController:vc animated:YES];
                }
            }
        }
    }else if (alertView.tag == 3){
        NSLog(@"点击了推送通知");
        [self.window.rootViewController presentViewController:[[UIViewController alloc]init] animated:YES completion:nil];
    }else if (alertView.tag == 5){
        
        if (buttonIndex == 1) {
            QActivityWebVC *web = [[QActivityWebVC alloc]init];
            [[QViewUtility getCurrentVC].navigationController pushViewController:web animated:YES];
            web.url = _url;
        }
    }
    else{
//        QAllOrderMoreVC *vc = [[QAllOrderMoreVC alloc]init];
//        NSLog(@"%ld",alertView.tag);
//        PushVC *vc = [[PushVC alloc]init];
//        vc.view.backgroundColor = [UIColor whiteColor];
//        [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
    }
}


#pragma mark ---- 微信支付回调
- (void)onResp:(BaseResp *)resp{

    if([resp isKindOfClass:[PayResp class]]){
        switch (resp.errCode) {
            case WXSuccess:
                CLog(@"支付成功");
                if([[QUserInfo sharedInfo].payTypeStr isEqualToString:paytopup]){//充值***********
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTopUpMoneySuccess object:nil];
                    QLoginModel *logModel = [QUserInfo sharedInfo].loginModel;
                    logModel.level = @"1";
                    
                    [QDataUtility updateLoginModel:logModel];
                }else if ([[QUserInfo sharedInfo].payTypeStr isEqualToString:payorder]){//支付订单
                    QNavigationVC *nav = (QNavigationVC *)self.window.rootViewController;
                    QPaySuccessVC *vc = [[QPaySuccessVC alloc] init];
                    [nav pushViewController:vc animated:YES];
                }
                break;
                
            default:
                CLog(@"支付失败");
                break;
        }
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{

    [WXApi handleOpenURL:url delegate:self];
    return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation{
    if([url.host isEqualToString:@"pay"]){//微信
        [WXApi handleOpenURL:url delegate:self];
        return YES;
    }else if([url.host isEqualToString:@"safepay"]){//支付宝
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            CLog(@"resultDic====%@",resultDic);
        }];
        return YES;
    }else{
        return [UMSocialSnsService handleOpenURL:url];
    }
    return YES;
}

//ios9以后的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            CLog(@"resultDic====%@",resultDic);
        }];
    }else if ([url.host isEqualToString:@"pay"]){//微信
        [WXApi handleOpenURL:url delegate:self];
        return YES;
    }
    return YES;
}

- (void)reciveRegistrationId:(NSNotification *)notification{
    CLog(@"极光登录成功 registrationID : %@",[JPUSHService registrationID]);
}

#pragma mark---JPush
// 3.注册 DeviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [JPUSHService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    //判断app是不是在前台运行，有三个状态(如果不进行判断处理，当你的app在前台运行时，收到推送时，通知栏不会弹出提示的)
    // UIApplicationStateActive, 在前台运行
    // UIApplicationStateInactive,未启动app
    //UIApplicationStateBackground    app在后台
    
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {  //此时app在前台运行，我的做法是弹出一个alert，告诉用户有一条推送，用户可以选择查看或者忽略
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"推送消息"
                                                         message:@"您有一条新的推送消息!"
                                                        delegate:self
                                               cancelButtonTitle:@"取消"
                                               otherButtonTitles:@"查看",nil];
        alert.tag = 4;
        [alert show];
        
    }else {
        
        NSLog(@"userInfo:%@",userInfo);
        
    //这里是app未运行或者在后台，通过点击手机通知栏的推送消息打开app时可以在这里进行处理，比如，拿到推送里的内容或者附加      字段(假设，推送里附加了一个url为 www.baidu.com)，那么你就可以拿到这个url，然后进行跳转到相应店web页，当然，不一定必须是web页，也可以是你app里的任意一个controll，跳转的话用navigation或者模态视图都可以
}

//这里设置app的图片的角标为0，红色但角标就会消失
[UIApplication sharedApplication].applicationIconBadgeNumber  =  0;
completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark--- Jpush 自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary * userInfo = [notification userInfo];
    NSDictionary *userDic = [userInfo objectForKey:@"extras"];
    CLog(@"==push==%@",userDic);
    NSString *type = userDic[@"type"];
    NSString *orderState = userDic[@"state"];
    [self whoIsPage:userInfo type:type orderState:orderState];

}

//通知的公有方法

- (void)whoIsPage:(NSDictionary *)userInfo type:(NSString *)type orderState:(NSString *)orderState{
    
    NSDictionary *userDic = [userInfo objectForKey:@"extras"];
    NSString *content = userDic[@"content"];
    if ([type isEqualToString:@"1"]) {
        //异地登录
        [QDataUtility deleteLoginModel];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBar4 object:nil];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"异地登录提醒" message:content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即登录", nil];
        alert.tag = 2;
        [alert show];

    }else if ([type isEqualToString:@"4"]){
        //订单类推送
        NSString *orderId = userDic[@"orderId"];
        if ([orderState isEqualToString:@"orderState_2"]) {//2配送中
            
            //不在本页时跳转
            if ([QUserInfo sharedInfo].isWhoPage == NO) {
                QSendingMapVC *vc = [[QSendingMapVC alloc] init];
                vc.orderId = orderId;
                [[QViewUtility getCurrentVC].navigationController pushViewController:vc animated:YES];
            }
            
        }else if ([orderState isEqualToString:@"orderState_6"]){//6待支付
            //支付
            QPushModel *model = [QPushModel objectFromDict:userDic];
            
            [QViewUtility showPushBoxViewWithModel:model myBlock:^(NSInteger index) {
                if (index == 2) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationGoToPay" object:nil];
                    [QViewUtility getCurrentVC].tabBarController.selectedIndex = 1;
                }
            }];
        }
        else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:content btnTitle:@"我已知晓" type:1 myBlock:^{
                 [QViewUtility getCurrentVC].tabBarController.selectedIndex = 2;
            }];
        }
        
    }else{
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"推送消息"
                                                         message:@"您有一条新的推送消息!"
                                                        delegate:self
                                               cancelButtonTitle:@"取消"
                                               otherButtonTitles:@"查看",nil];
        alert.tag = 5;
        [alert show];
        
    }
    
}
// iOS 10 Support，前台收到通知，后台不会执行这个方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler{

    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"userInfo:%@",userInfo);
    if ([userInfo.allKeys containsObject:@"content"]) {
        _url = [userInfo objectForKey:@"content"];
    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        /// iOS10处理远程推送
        [JPUSHService handleRemoteNotification:userInfo];

        NSDictionary *dic = [userInfo objectForKey:@"aps"];
        NSString *str = [dic objectForKey:@"alert"];
        if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
        {  //此时app在前台运行，我的做法是弹出一个alert，告诉用户有一条推送，用户可以选择查看或者忽略
          
            
//            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"推送消息" message:str preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
//            [alertController addAction:cancelAction];
//            [alertController addAction:okAction];
//            [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
        }
    }else{
        /// 应用处于前台收到本地通知不会出现在通知中心 借用极光推送的方法将本地通知添加到通知栏 ==============================
        completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
    }
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置

}
// iOS 10 Support，用户点击了通知进入app
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{

    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"userInfobg:%@",userInfo);
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        /// 杀死，后台点击通知栏 处理远程推送的跳转
        [self reciveNotification:userInfo];
    }else{
        /// 前台运行时 转的本地通知 直接通知栏弹窗进行跳转处理
        [self reciveNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)reciveNotification:(NSDictionary *)userInfo
{
   
    NSString *url = [userInfo objectForKey:@"content"];
    QActivityWebVC *web = [[QActivityWebVC alloc]init];
    [[QViewUtility getCurrentVC].navigationController pushViewController:web animated:YES];
    web.url = url;
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    CLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

-(void)applicationWillEnterForeground:(UIApplication *)application{
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    [JPUSHService setBadge:0];
}

// 接收到内存警告的时候调用
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    // 停止所有的下载
    [[SDWebImageManager sharedManager] cancelAll];
    // 删除缓存
    [[SDWebImageManager sharedManager].imageCache clearMemory];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [self maskAction];
    [QUserInfo sharedInfo].isShow = NO;
    [self removePayOrderListView];
    _first = @"second";//解决每个页面发送通知第一次打开程序出现两次
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    if([QUserInfo sharedInfo].loginModel){
        if([QUserInfo sharedInfo].isShow == NO && [_first isEqualToString:@"second"]){
            //[self requestNoPayOrderData];
        }
    }
}

//未支付订单13638671251
//- (void)requestNoPayOrderData{
//    NSString *url = [QParamService urlWithAction:@"getOrderStateNum"];
//    NSDictionary *param = [QParamService noPayOrder];
//    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
//        if(error){
//            return;
//        }
//        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
//        if([basModel.result isEqualToString:@"success"]){
//            NSDictionary *d = basModel.items;
//            if(d.count){
//                QNoPayOrderModel *model = [QNoPayOrderModel objectFromDict:basModel.items];
//                [self removePayOrderListView];//移除列表弹框
//                [QViewUtility showMorePlayPayViewAmount:model.amount data:model.list myBlock:^(NSInteger index) {
//                    if(index == 0){
//                        [QUserInfo sharedInfo].isShow = YES;
//                    }
//                    _orderId = model.orderIds;
//                    CLog(@"====%ld",index);
//                    if(index == 1){
//                        _moneys = model.amount;
//                        [self showPayViewMoney];
//                    }
//                }];
//            }else{
//            }
//        }else{
//        }
//    }];
//}

//移除列表弹框
- (void)removePayOrderListView{
    UIWindow *window = [UIApplication sharedApplication].windows.lastObject;
    UIControl *v = (UIControl *)[window viewWithTag:2016];
    if(v){
        [v removeFromSuperview];
    }
}

#pragma mark -- 支付
- (void)paywayWithurl:(NSString *)url{
    if(_passWordStr.length > 0){
        NSString *md5Str = [QMD5Hash md5String:_passWordStr];
        md5Str = [md5Str uppercaseString];
        _passWordStr = md5Str;
    }
    
    NSDictionary *param = [QParamService payWithorderId:_orderId paymentStatus:@"4" payPassWord:_passWordStr draweeTel:nil couponCode:@""];
    [QViewUtility showMBHudToView:self.window hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        _passWordStr = @"";
        [QViewUtility hideMBHudToView:self.window];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [self maskAction];
             QNavigationVC *nav = (QNavigationVC *)self.window.rootViewController;
            [QUserInfo sharedInfo].payTypeStr = payorder;
            QPaySuccessVC *vc = [[QPaySuccessVC alloc] initWithNibName:@"QPaySuccessVC" bundle:nil];
            [QUserInfo sharedInfo].isShow = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTopUpMoneySuccess object:nil];
            [nav pushViewController:vc animated:YES];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

////弹出13638671251
- (void)showPayViewMoney{
    
        UIWindow *window = [[UIApplication sharedApplication].delegate window];
         [window addSubview:_maskView];
        _maskView.hidden = NO;
        _playView.payMoneyStr = _moneys;
        _playView.yuMoney = [QUserInfo sharedInfo].loginModel.balance;
        _maskView.alpha = 0;
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
            _maskView.alpha = 1;
        } completion:^(BOOL finished) {
        }];
}

//#pragma mark -- 隐藏支付框
- (void)maskAction{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    _maskView.alpha = 1;
    [UIView animateWithDuration:.3 animations:^{
        _maskView.alpha = 0;
    } completion:^(BOOL finished) {
        _maskView.hidden = YES;
    }];
}

- (void)createNopayView{
    __block AppDelegate *wself = self;
    _maskView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _maskView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    [_maskView addTarget:self action:@selector(maskAction) forControlEvents:UIControlEventTouchUpInside];
    
    _playView = [[QPayPlayBoxView alloc] init];
    [_maskView addSubview:_playView];
    
    _maskView.hidden = YES;

    _playView.StrBlock = ^(NSString *str){
        CLog(@"str====%@",str);
        _passWordStr = str;
    };
    _playView.NotiBlock = ^(NSInteger tag){
        CLog(@"确定支付");
        if(tag == 1){//忘记密码
            QForgetPayPassWordVC *vc = [[QForgetPayPassWordVC alloc] initWithNibName:@"QForgetPayPassWordVC" bundle:nil];
                [wself maskAction];
            vc.block = ^(){
                [wself showPayViewMoney];
            };
            _passWordStr = @"";
            QNavigationVC *nav = (QNavigationVC *)wself.window.rootViewController;
            [nav pushViewController:vc animated:YES];
        }else if (tag == 2){//支付
            if(_passWordStr.length < 4){
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"支付密码错误,请重新输入" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
                return ;
            }
            NSString *url = [QParamService urlWithAction:@"submitOrder"];
            [wself paywayWithurl:url];
        }
    };
}
- (void)ExceptionHandling{
    
    InstallUncaughtExceptionHandler().showAlert(YES).logFileHandle(^(NSString *path) {
        
        //path：日志文件的路径，日志是一个名字为“ExceptionLog_sp”的“txt”文件
        //也可用这种方法获得路径：[[SPUncaughtExceptionHandler shareInstance]exceptionFilePath]
        //每次异常都会调用该block
        
        NSLog(@"%@",path);
        //模拟耗时操作
        [NSThread sleepForTimeInterval:2.0];
        
        //处理完成后调用（如果不调用则程序不会退出）主要是为了处理耗时操作
        ExceptionHandlerFinishNotify();
        
    }).showExceptionInfor(YES).didClick(^(NSString *ExceptionMessage){
        
        //点击（继续）后的处理，比如将崩溃信息上传到服务器，该字符串为：异常信息
        NSLog(@"%@",ExceptionMessage);
        
    }).message(@"链式编程自定义，如果需要自定义message，须将showExceptionInfor设置为NO").title(@"抱歉，程序出现了异常，请联系我们");
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
